package com.yonyou.brigade.third_parties.ctrip.bigcustomer.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.brigade.third_parties.ctrip.bigcustomer.model.CtripBigUser;
import com.yonyou.brigade.third_parties.ctrip.model.CtripConfig;
import com.yonyou.brigade.third_parties.third.model.BriDeptAuthorization;
import com.yonyou.brigade.third_parties.third.model.BriThirdProperty;
import com.yonyou.ybzboot.starter.common.exception.BaseException;
import corp.openapicalls.contract.employee.*;
import corp.openapicalls.contract.ordercontroller.ticket.OrderSearchTicketResponse;
import corp.openapicalls.service.employee.MultipleEmployeeSyncService;
import corp.openapicalls.service.ticket.CorpTicketService;
import org.apache.commons.collections4.ListUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class EmployeeSyncUtils {

    private static Logger  logger = LoggerFactory.getLogger(EmployeeSyncUtils.class);

    /**
     *
     * @Title: buildSaveCorpCustInfoList
     * @Description: 构建批量人事更新契约请求
     * @param @param ticket
     * @param @return    设定文件
     * @return SaveCorpCustInfoList    返回类型
     * @throws
     */
    public static AuthenticationListRequst buildAuthenticationListRequst(String ticket, List<CtripBigUser> ctripUsers, CtripConfig ctripMaster, List<BriDeptAuthorization> deptAuths, boolean auth, List<BriThirdProperty> thirdProperties){
        AuthenticationListRequst authenticationListRequst=new AuthenticationListRequst();
        authenticationListRequst.setTicket(ticket);
        authenticationListRequst.setCorporationID(ctripMaster.getCorporationId());
        List<AuthenticationInfoList> authenticationInfoLists=new ArrayList<>();
        for (CtripBigUser ctripUser:ctripUsers) {
            Authentication authencationEntity=new Authentication();
            authencationEntity.setEmployeeID(ctripUser.getPersonCode());//用户员工编码用员工编号
            authencationEntity.setCorporationID(ctripMaster.getCorporationId());
            authencationEntity.setName(ctripUser.getUserName());
            authencationEntity.setEmail(ctripUser.getEmail());
            authencationEntity.setMobilePhone(ctripUser.getPhone());
            if(!StringUtils.isEmpty(ctripUser.getEmail())) {
                authencationEntity.setIsSendEMail(true);
            }
            else
            {
                authencationEntity.setIsSendEMail(false);
            }
            authencationEntity.setValid(ctripUser.getValid()==1?"A":"I");//在职情况 (A-在职,I-离职)
            if(!StringUtils.isEmpty(ctripUser.getOrgName())) {
                authencationEntity.setDept1(ctripUser.getOrgName());
            }
            authencationEntity.setDept2(ctripUser.getDeptName());
            /*if(!StringUtil.isEmpty(ctripUser.getRankname()))
            {
                authencationEntity.setRankName(ctripUser.getRankname());
            }*/
//            if (!StringUtils.isEmpty(ctripUser.getPostName())){
//                authencationEntity.setRankName(ctripUser.getPostName());
//            }else {
//                authencationEntity.setRankName("未知职务");
//            }
            if (ctripUser.getIsBookClass()!=null)
                authencationEntity.setIsBookClass(ctripUser.getIsBookClass());
            if (ctripUser.getIntlBookClassBlock()!=null)
                authencationEntity.setIntlBookClassBlock(ctripUser.getIntlBookClassBlock());

            authencationEntity.setDept3("");
            if(thirdProperties!=null&&thirdProperties.size()>0)
            {
                for(int i=0;i<thirdProperties.size();i++)
                {
                    try {
                        Field f = authencationEntity.getClass().getDeclaredField(lowerName(thirdProperties.get(i).getKey()));
                        f.setAccessible(true);
                        if(thirdProperties.get(i).getType().equals("INTEGER"))
                        {
                            int value= Integer.parseInt(thirdProperties.get(i).getValue());
                            f.set(authencationEntity,value);
                        }
                        else {
                            f.set(authencationEntity, thirdProperties.get(i).getValue());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error(e.getMessage());
                    }
                }
            }
            if(auth) {
                if (StringUtils.isEmpty(ctripUser.getDestEmail())) {
                    if (!StringUtils.isEmpty(ctripUser.getDeptId()) && deptAuths != null && deptAuths.size() > 0) {
                        List<BriDeptAuthorization> tempdeptAuth = deptAuths.stream().filter(s -> s.getDeptPk().equals(ctripUser.getDeptId())).collect(Collectors.toList());
                        if (tempdeptAuth != null && tempdeptAuth.size() > 0) {
                            authencationEntity.setConfirmPerson2(tempdeptAuth.get(0).getEmail());
                        }
                    }
                } else {
                    authencationEntity.setConfirmPerson2(ctripUser.getDestEmail());
                }
            }
            authencationEntity.setSubAccountName(ctripMaster.getSubAccountName());
            AuthenticationInfoList authenticationInfoList=new AuthenticationInfoList();
            authenticationInfoList.setAuthentication(authencationEntity);
            authenticationInfoList.setSequence("0");
            authenticationInfoLists.add(authenticationInfoList);
        }
        authenticationListRequst.setAppkey(ctripMaster.getAppKey());
        authenticationListRequst.setAuthenticationInfoList(authenticationInfoLists);
        return authenticationListRequst;
    }



    public static void multipleEmployeeWithAuthSync(List<CtripBigUser> ctripUsers, CtripConfig ctripMaster, List<BriDeptAuthorization> deptAuths, boolean auth , List<BriThirdProperty> thirdProperties){
        OrderSearchTicketResponse ticketResponse= CorpTicketService.getEmployeeSyncTicket(ctripMaster.getAppKey(), ctripMaster.getAppSecurity(), "1.0");
        if(ticketResponse!=null&&ticketResponse.getStatus()!=null&&ticketResponse.getStatus().getSuccess())
        {
            logger.info("get ticket success! ticket:"+ticketResponse.getTicket());
            AuthenticationListRequst authenticationListRequst = null;
            List<List<CtripBigUser>> lists = ListUtils.partition(ctripUsers, 500);
            for (List<CtripBigUser> ctripUserBatch : lists) {
                authenticationListRequst = buildAuthenticationListRequst(ticketResponse.getTicket(), ctripUserBatch, ctripMaster,deptAuths,auth,thirdProperties);
                multipleUsersSync(authenticationListRequst);
            }
        }
        else{
            String errorms = String.format("get ticket failed! error message:%s", JSON.toJSONString(ticketResponse));
            logger.info("get ticket failed! error message:%s", JSON.toJSONString(ticketResponse));
            throw new RuntimeException(errorms);
        }
    }

    public static boolean multipleUsersSync(AuthenticationListRequst authenticationListRequst) {
        boolean success=false;
        AuthenticationInfoListResponse authenticationInfoListResponse;
        MultipleEmployeeSyncService empoyeeSyncService=new MultipleEmployeeSyncService();
        authenticationInfoListResponse=empoyeeSyncService.MultipleEmployeeSync(authenticationListRequst);
        if(authenticationInfoListResponse!=null)
        {
            String result= authenticationInfoListResponse.getResult();
            if("Failed".equals(result))
            {
                String errorResult="";
                List<ErrorMessage> errorMessages=authenticationInfoListResponse.getErrorMessageList();
                if(!errorMessages.isEmpty())
                {
                    for (ErrorMessage errorMessage : errorMessages) {
                        errorResult+=errorMessage;
                        logger.info(JSONObject.toJSONString(errorMessage));
                    }
                }
            }
            else
            {
                success=true;
            }
            logger.info(authenticationInfoListResponse.getResult());
        }

        return success;
    }

    //首字母大写
    public static String lowerName(String name) {
        char[] cs = name.toCharArray();
        cs[0] += 32;
        return String.valueOf(cs);

    }
}
